﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Kugar.SL4.Core.Locker
{
    public class SynInvokeRIA
    {

        private int waitTimeOut = 0;

        public SynInvokeRIA()
        {
            waitTimeOut = 0;
        }

        public SynInvokeRIA(int timeOut)
        {
            waitTimeOut = timeOut;
            bgw.DoWork += Dowork;
            //bgw.RunWorkerCompleted += ProcessComplete;
            InvokeList = new List<Action>();
        }

        private BackgroundWorker bgw = new BackgroundWorker();
        private AutoResetEvent au = null;

        public void Invoke()
        {
            bgw.RunWorkerAsync();
        }

        public void InvokeAndClean()
        {
            Invoke();

            InvokeList.Clear();
        }

        public void UnLock()
        {
            au.Set();
        }

        private bool _breakContinue=false;
        public void BreakContinue()
        {
            _breakContinue = true;
        }

        public List<Action> InvokeList { private set; get; }

        public event EventHandler ProcessComplete;

        private void Dowork(object sender, EventArgs e)
        {
            lock (InvokeList)
            {
                try
                {
                    if (InvokeList.Count <= 0)
                    {
                        return;
                    }

                    _breakContinue = false;

                    au = new AutoResetEvent(false);


                    for (var i = 0; i < InvokeList.Count; i++)
                    {
                        InvokeList[i].Invoke();

                        au.WaitOne(waitTimeOut);

                        if (_breakContinue)
                        {
                            break;
                        }
                    }     
                }
                finally
                {
                    if (ProcessComplete!=null)
                    {
                        ProcessComplete(this,new EventArgs());
                    }
                }

           
            }


        }


    }

}
